import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_reader_paging/flutter_reader_paging.dart';

import 'const/resource.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<String> textList;

  final key = GlobalKey();

  var currentFontSize = 12.0;

  var targetSize = 14.0;

  double fontSizeProvide() {
    return targetSize;
  }

  List<String> calcText(
    String text,
    double width,
    double maxHeight,
    double textSize, {
    String lineStart = "　　",
  }) {
    print("text.length = ${text.length}");
    final lineMax =
        ReaderPagingCalulator.lineMaxWidth(width, maxHeight, textSize);

    print("width = $width");
    print("maxHeight = $maxHeight");
    text = text.replaceAll("\n", "\n$lineStart");
    text = "$lineStart$text";

    final result = <String>[];

    var startIndex = 0;

    bool indexAdd = true;

    var m = 0;

    for (var i = 1; i < text.length;) {
      m++;
      final currentText = text.substring(startIndex, i);

      if (text[startIndex] == "\n") {
        startIndex++;
        i++;
        continue;
      }

      final painter = TextPainter(
        text: TextSpan(
          text: currentText,
          style: TextStyle(
            fontSize: fontSizeProvide(),
          ),
        ),
        textDirection: TextDirection.ltr,
      );

      painter.layout(minWidth: width, maxWidth: width);
      if (painter.size.height > maxHeight) {
        indexAdd = false;
      } else if (!indexAdd && painter.size.height <= maxHeight) {
        startIndex = i;
        result.add(currentText);
        // if (currentText[currentText.length - 1] == "\n") {
        //   startIndex++;
        // }
        indexAdd = true;
      } else {
        indexAdd = true;
      }

      if (indexAdd) {
        i += lineMax;
      } else {
        i--;
      }
    }

    result.add(text.substring(startIndex));

    print("for count = $m");

    return result;
  }

  void calc() async {
    var txt = await rootBundle.loadString(R.ASSET_01_TXT);

    RenderBox box = key.currentContext.findRenderObject();
    final maxHeight = box.constraints.maxHeight;
    final start = DateTime.now().millisecondsSinceEpoch;
    print("start = $start");
    final textList = calcText(
      txt,
      box.constraints.maxWidth,
      maxHeight,
      fontSizeProvide(),
    );
    final end = DateTime.now().millisecondsSinceEpoch;
    print("end = $end");
    print("diff duration = ${end - start}");

    // for (final t in textList) {
    //   print(t);
    // }

    this.textList = textList;

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var fontSize = fontSizeProvide();
    if (currentFontSize != fontSize) {
      calc();
      this.currentFontSize = fontSize;
    }
    final style = TextStyle(fontSize: fontSize);
    return Scaffold(
      appBar: AppBar(
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.add),
            onPressed: () => setState(() {
              targetSize++;
            }),
          ),
          IconButton(
            icon: Icon(Icons.remove),
            onPressed: () => setState(() {
              targetSize--;
            }),
          ),
          IconButton(
            icon: Icon(Icons.refresh),
            onPressed: calc,
          ),
        ],
      ),
      body: SafeArea(
        child: Stack(
          children: <Widget>[
            Container(
              color: Colors.yellow,
            ),
            Padding(
              padding: const EdgeInsets.all(15.0),
              child: PageView.builder(
                key: key,
                itemCount: textList?.length ?? 0,
                itemBuilder: (BuildContext context, int index) {
                  return Text(
                    textList[index],
                    style: style,
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
